package com.persistence;

import com.util.*;
import com.util.Error;
import com.file.FileManager;
import com.models.TableData;

import java.io.File;
import java.io.IOException;

/**
 * Created by timeliar on 15-9-29.
 *
 */
public enum DataPersistence {
    @SuppressWarnings("unused")
    INSTANCE;


    public static TableData getData(String tableName) {
        String path = Constants.TABLE_DATA.replace("*", tableName);
        try {
            Object object = FileManager.readObject(path);
            return (TableData) object;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void persistence(TableData... datas) {
        for (TableData tableData : datas) {
            try {
                FileManager.writeObject(tableData, Constants.TABLE_DATA.replace("*", tableData.getTable().getName()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void delete(String name) throws Error {
        File file = new File(Constants.TABLE_DATA.replace("*", name));
        if (!file.exists() || !file.delete()) {
            throw new Error(name + "not exist");
        }
    }
}
